/* eslint-disable no-undef */
let upplevels = {
  'xiaoqu':'cun',
  'cun':'xiang',
  'xiang':'xian',
  'xian':'shi',
  'shi':'sheng',
  'sheng':'china'
}

export function getupperlevel(level){
  return upplevels[level];
}

export let arealevel={
  0:'china',
  2:'sheng',
  4:'shi',
  6:'xian',
  9:'xiang',
  12:'cun',
  15:'xiaoqu'
}
export function getlevel(area){
  return arealevel[area.length]
}
export function savepic(domid, filename,localpic,that) {
  html2canvas(document.querySelector("#" + domid)).then((canvas) => {
    if(localpic){
      var imgData = canvas.toDataURL();
      //保存图片
      var saveFile = function (data, filename) {
        var save_link = document.createElementNS(
          "http://www.w3.org/1999/xhtml",
          "a"
        );
        save_link.href = data;
        save_link.download = filename;
  
        var event = document.createEvent("MouseEvents");
        event.initMouseEvent( "click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null );
        save_link.dispatchEvent(event);
      };
      //最终文件名+文件格式
      saveFile(imgData, filename);
    }
    else{
      canvas.toBlob((blob) => {
        // let imgfile = new File([blob], "fff", { type: "image/jpg" });
        //上传截图
        let formData = new FormData();
        formData.append("name", filename);
        formData.append("file", blob);
        console.log(formData);
        $.ajax({
          url: `http://${ipapi}/upload`,
          type: "post",
          processData: false,
          contentType: false,
          data:formData,
          success:function(){
            that.$message("图片上传成功");
          },error:function(){
            that.$message("图片上传失败");
          }
        });
      });
    }
    
  });
}
export function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return false;
}
export function gradientColor(startColor, endColor, step) {
  var startRGB = colorRgb(startColor); //转换为rgb数组模式
  var startR = startRGB[0];
  var startG = startRGB[1];
  var startB = startRGB[2];
  var endRGB = colorRgb(endColor);
  var endR = endRGB[0];
  var endG = endRGB[1];
  var endB = endRGB[2];
  var sR = (endR - startR) / step; //总差值
  var sG = (endG - startG) / step;
  var sB = (endB - startB) / step;
  var colorArr = [];
  for (var i = 0; i < step; i++) {
    //计算每一步的hex值
    var hex = colorHex(
      "rgb(" +
        parseInt(sR * i + startR) +
        "," +
        parseInt(sG * i + startG) +
        "," +
        parseInt(sB * i + startB) +
        ")"
    );
    colorArr.push(hex);
  }
  return colorArr;
}
// 将hex表示方式转换为rgb表示方式(这里返回rgb数组模式)
function colorRgb(sColor) {
  var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  sColor = sColor.toLowerCase();
  if (sColor && reg.test(sColor)) {
    if (sColor.length === 4) {
      var sColorNew = "#";
      for (let i = 1; i < 4; i += 1) {
        sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
      }
      sColor = sColorNew;
    }
    //处理六位的颜色值
    var sColorChange = [];
    for (var i = 1; i < 7; i += 2) {
      sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
    }
    return sColorChange;
  } else {
    return sColor;
  }
}
// 将rgb表示方式转换为hex表示方式
function colorHex(rgb) {
  var _this = rgb;
  var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  if (/^(rgb|RGB)/.test(_this)) {
    var aColor = _this.replace(/(?:(|)|rgb|RGB)*/g, "").split(",");
    var strHex = "#";
    for (var i = 0; i < aColor.length; i++) {
      var hex = Number(aColor[i]).toString(16);
      hex = hex < 10 ? 0 + "" + hex : hex; // 保证每个rgb的值为2位
      if (hex === "0") {
        hex += hex;
      }
      strHex += hex;
    }
    if (strHex.length !== 7) {
      strHex = _this;
    }
    return strHex;
  } else if (reg.test(_this)) {
    var aNum = _this.replace(/#/, "").split("");
    if (aNum.length === 6) {
      return _this;
    } else if (aNum.length === 3) {
      var numHex = "#";
      for (let i = 0; i < aNum.length; i += 1) {
        numHex += aNum[i] + aNum[i];
      }
      return numHex;
    }
  } else {
    return _this;
  }
}

export function gradientValue(min, max, step) {
  let vals = [];
  for (let i = 0; i < step; i++) {
    vals.push(min + ((max - min) * (i + 1)) / (step + 1));
  }
  return vals;
}

export function quantileValue(values, step) {
  values = values.sort((a, b) => a - b);
  let vals = [],
    len = values.length;
  let space = (len * 1.0) / (step + 1);
  // console.log(values)
  for (let i = 0; i < step; i++) {
    vals.push(values[parseInt((i + 1) * space)]);
    // console.log(parseInt((i+1)*space),values[parseInt((i+1)*space)]);
  }
  // console.log(values[0],values[values.length-1],step,space,vals)
  return vals;
}

export function randomcolorrender(geodata) {
  function randomHexColor() {
    //随机生成十六进制颜色
    return (
      "#" +
      ("00000" + ((Math.random() * 0x1000000) << 0).toString(16)).substr(-6)
    );
  }
  let colorrender = ["match", ["get", "code"]];
  geodata.features.forEach((ft) => {
    colorrender.push(ft.properties["code"], randomHexColor());
  });
  colorrender.push("rgba(0, 0, 0, 0)");
  return colorrender;
  //   console.log(colorrender)
}

export async function geodata(level,fields,filter){
  let url_geo = encodeURI(
    `http://${ipapi}/geoserver/rp7/ows?service=WFS&version=1.0.0&request=GetFeature&outputFormat=application/json&typeName=rp7:gv_${level}&propertyName=geom,${fields??'code,codename'}&cql_filter=${filter??'1=1'}&format_options=id_policy:reference_no=false`
  );
  let res = await $.getJSON(url_geo);
  // console.log(res)
  return res;
}

export async function nodeapi(method,option,type){
  let url_geo = encodeURI( `http://${ipapi}/${method}` );
  let res = await $.ajax({
    type:type??'get',
    timeout: 1000000,
    url: url_geo,
    data: option,
    dataType: "json",
  });
  return res;
}

export function swap(arr, index1, index2) {
  arr[index1] = arr.splice(index2, 1, arr[index1])[0];
  return arr;
}

export function getfilter(area) {
  return `code like '${area ? globalarea : area}%'`;
}